package com.sc.byahi.user.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.KeyFactory;
import com.sc.byahi.user.shared.Profile;
import com.sc.byahi.user.shared.SharedUtil;

public class TaskResize extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger logger = Logger.getLogger("com.sc.byahi.user.server.TaskResize");

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String profileId = req.getParameter("profileid");
		Long pId = SharedUtil.getLong(profileId);
		executeTask(pId);
	}

	private void executeTask(Long profileId) {
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

		Entity p;
		try {
			p = datastore.get(KeyFactory.createKey(Profile.class.getSimpleName(), profileId));
			Object imagesObj = p.getProperty(Profile.IMAGES);
			List<BlobKey> images = new ArrayList<BlobKey>();
			if (imagesObj != null) {
				for (String key : (List<String>) imagesObj) {
					BlobKey oldImageBlobKey = new BlobKey(key);
					images.add(oldImageBlobKey);
				}
			}
			List<BlobKey> response = StoreUtil.resizeAndUploadImages(images, profileId + "");
			logger.log(Level.WARNING, "Saving resized images to profile." + response);
			StoreUtil.replaceProfileImages(response, datastore, p);
		} catch (EntityNotFoundException e) {
			logger.log(Level.SEVERE, "Exception while uploading resized images: ", e);
		}
	}
}
